/* USER CODE BEGIN Header */
/**
 ******************************************************************************
 * @file           : main.c
 * @brief          : Main program body
 ******************************************************************************
 * @attention
 *
 * Copyright (c) 2023 STMicroelectronics.
 * All rights reserved.
 *
 * This software is licensed under terms that can be found in the LICENSE file
 * in the root directory of this software component.
 * If no LICENSE file comes with this software, it is provided AS-IS.
 *
 ******************************************************************************
 */
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "main.h"
#include "usb_device.h"
#include "gpio.h"

/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
#include "Leds.h"
#include "usb_device.h"
#include "usbd_cdc_if.h"
#include "Ymodem.h"
#include "rtthread.h"
#include "inflash.h"
#include "Usb_Control.h"
#include "crc.h"
#include "rs485.h"
#include "lwip.h"
#include "zy_udp.h"
#include "eeprom.h"
#include "ee_parameter.h"

/* USER CODE END Includes */

/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN PTD */

/* USER CODE END PTD */

/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */

/* USER CODE END PD */

/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN PM */

/* USER CODE END PM */

/* Private variables ---------------------------------------------------------*/

/* USER CODE BEGIN PV */
typedef  void (*pFunction)(void);
static rt_thread_t thread_default_id,thread_rym_id;
uint32_t ledFre = 600;
uint8_t ymRxBuf[YM_BUFSIZE];
uint8_t ymTxBuf[YM_BUFSIZE];
gqueue_t qYmRx,qYmTx;
uint8_t ymPipe = PIPE_NONE;

void Thread_Default_Entry(void* paramter);
void Thread_Rym_Entry(void* parameter);

uint32_t Check_App(void)
{
    uint32_t appCrc32Calc = 0,appCrc32Read = 0;
    appCrc32Calc =Calc_APP_Crc32();
    InFLASH_Read(APP_CRC32_ADDR, &appCrc32Read, 4);
    return (appCrc32Calc == appCrc32Read);

}

uint32_t Restore_App(void)
{
    uint32_t appCrc32Calc = 0,appCrc32Read = 0;
    appCrc32Calc =Calc_Backup_APP_Crc32();
    InFLASH_Read(APP_CRC32_ADDR, &appCrc32Read, 4);
    InFlash_Erase(APP_ADDR,APP_LENGTH);
    if(appCrc32Calc == appCrc32Read){       // 可以恢复app

        InFLASH_Write(APP_ADDR,(uint32_t*)APP_BACKUP_ADDR,APP_LENGTH);
        return 1;
    }else {
        return 0;
    }
}

void Backup_App(void)
{
    InFLASH_Write(APP_BACKUP_ADDR,(uint32_t*)APP_ADDR,APP_LENGTH);
}

pFunction Jump_To_Application;
void IapRunApp(void)
{
    uint32_t JumpAddress;
    if (((*(__IO uint32_t*)APP_ADDR) & 0x2FFE0000) == 0x20000000 || \
        *((__IO uint32_t*)APP_ADDR) == 0x20020000)    //gcc生成的代码栈顶是在ram的最高地�??????
    {
#ifndef DEBUG_APP
        if(!Check_App())  // 程序不完�????
        {
            if(!Restore_App()){
                return;
            }

        }
#endif
        __set_PRIMASK(1);
//      HAL_DeInit();
        /* Jump to user application */
        JumpAddress = *(__IO uint32_t*) (APP_ADDR + 4);
        Jump_To_Application = (pFunction) JumpAddress;
        /* Initialize user application's Stack Pointer */
//       __set_CONTROL(0);      //由于在boot中使用了rtthread，需要将堆栈置为主堆�??????
//      __set_MSP(*(__IO uint32_t*) UPDATE_APP_ADDRESS);
        Jump_To_Application();
    }
}

// 从RT_Thread任务中启动APP
void IapRunAppRT(void)
{
    uint32_t JumpAddress;
    if (((*(__IO uint32_t*)APP_ADDR) & 0x2FFE0000) == 0x20000000 || \
        *((__IO uint32_t*)APP_ADDR) == 0x20020000)    //gcc生成的代码栈顶是在ram的最高地�?????
    {
#ifndef DEBUG_APP
        if(!Check_App())  // 程序不完�????
        {
            if(!Restore_App()){
                return;
            }

        }
#endif
        __set_PRIMASK(1);
        HAL_DeInit();
        /* Jump to user application */
        JumpAddress = *(__IO uint32_t*) (APP_ADDR + 4);
        Jump_To_Application = (pFunction) JumpAddress;
        /* Initialize user application's Stack Pointer */
         __set_CONTROL(0);      //由于在boot中使用了rtthread，需要将堆栈置为主堆�??????
        __set_MSP(*(__IO uint32_t*) APP_ADDR);
        Jump_To_Application();
    }
}
/* USER CODE END PV */

/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
/* USER CODE BEGIN PFP */
char HARDVER = 0x30;
const port_pin_t hardVerPort[] =
{
    {VER_1_GPIO_Port,VER_1_Pin},
    {VER_2_GPIO_Port,VER_2_Pin},
    {VER_3_GPIO_Port,VER_3_Pin}
};

char Read_HardVer(void)
{
    int hardVer = 0;
    for(int i=0;i<sizeof(hardVerPort)/sizeof(port_pin_t);i++){
        if(HAL_GPIO_ReadPin(hardVerPort[i].port, hardVerPort[i].pin) == GPIO_PIN_RESET){
            hardVer |= (1<<i);
        }
    }
    return hardVer;
}
/* USER CODE END PFP */

/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */

/* USER CODE END 0 */

/**
  * @brief  The application entry point.
  * @retval int
  */
int main(void)
{

  /* USER CODE BEGIN 1 */

  /* USER CODE END 1 */

  /* MCU Configuration--------------------------------------------------------*/

  /* Reset of all peripherals, Initializes the Flash interface and the Systick. */
  HAL_Init();

  /* USER CODE BEGIN Init */

  /* USER CODE END Init */

  /* Configure the system clock */
  SystemClock_Config();

  /* USER CODE BEGIN SysInit */
//  EE_Init();
  EEP_ReadAll();
  gqueue_init(&qYmRx,ymRxBuf,YM_BUFSIZE,1);
  gqueue_init(&qYmTx,ymTxBuf,YM_BUFSIZE,1);
  Usb_Reconnect();
  /* USER CODE END SysInit */

  /* Initialize all configured peripherals */
  MX_GPIO_Init();
  MX_USB_DEVICE_Init();
  /* USER CODE BEGIN 2 */
  RS485_Init();
  MX_LWIP_Init();
  ZY_UdpInit();
  // 读取硬件版本
  HARDVER = Read_HardVer();


  thread_default_id = rt_thread_create("default",
                                          Thread_Default_Entry,
                                          RT_NULL,
                                          DEFAULT_STACK_SIZE,
                                          DEFAULT_PRIORITY,
                                          DEFAULT_TIME_SLICE);
  if(thread_default_id != RT_NULL)
  {
      rt_thread_startup(thread_default_id);
  }

  thread_rym_id = rt_thread_create("rym",
                                          Thread_Rym_Entry,
                                          RT_NULL,
                                          RYM_DOWN_STACK_SIZE,
                                          RYM_DOWN_PRIORITY,
                                          RYM_DOWN_TIME_SLICE);
  if(thread_rym_id != RT_NULL)
  {
      rt_thread_startup(thread_rym_id);
  }

  /* USER CODE END 2 */

  /* Infinite loop */
  /* USER CODE BEGIN WHILE */
//    while (1)
//    {
    /* USER CODE END WHILE */

    /* USER CODE BEGIN 3 */
//    }
  /* USER CODE END 3 */
}

/**
  * @brief System Clock Configuration
  * @retval None
  */
void SystemClock_Config(void)
{
  RCC_OscInitTypeDef RCC_OscInitStruct = {0};
  RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};

  /** Configure the main internal regulator output voltage
  */
  __HAL_RCC_PWR_CLK_ENABLE();
  __HAL_PWR_VOLTAGESCALING_CONFIG(PWR_REGULATOR_VOLTAGE_SCALE1);

  /** Initializes the RCC Oscillators according to the specified parameters
  * in the RCC_OscInitTypeDef structure.
  */
  RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE;
  RCC_OscInitStruct.HSEState = RCC_HSE_ON;
  RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
  RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE;
  RCC_OscInitStruct.PLL.PLLM = 25;
  RCC_OscInitStruct.PLL.PLLN = 336;
  RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV2;
  RCC_OscInitStruct.PLL.PLLQ = 7;
  if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
  {
    Error_Handler();
  }

  /** Initializes the CPU, AHB and APB buses clocks
  */
  RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
                              |RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2;
  RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
  RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
  RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV4;
  RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV2;

  if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_5) != HAL_OK)
  {
    Error_Handler();
  }
}

/* USER CODE BEGIN 4 */
struct rt_semaphore semYmSendCplt;
void Ym_Send_Ready(void)
{
    rt_sem_release(&semYmSendCplt);
}

//uint32_t downLoadStartTick = 0;
void Thread_Default_Entry(void* paramter)
{
    uint32_t ledTick = 0;
    uint8_t whichLed = 0;
    uint8_t ymSendBuf[64] = {0};
    size_t popSize;
    rt_sem_init(&semYmSendCplt,"semYmSendCplt", 0 ,RT_IPC_FLAG_FIFO);
    rt_sem_release(&semYmSendCplt);

    while(1)
    {
        if(rym_send_ready() == RT_EOK)
        {
            while(gqueue_pop_multiple_most(&qYmTx,ymSendBuf,64,&popSize) == 0)
            {
                rt_sem_take(&semYmSendCplt,50);
                if(ymPipe == PIPE_VCP)
                {
                    CDC_Transmit_FS(ymSendBuf,popSize);
                }
                else if(ymPipe == PIPE_485)
                {
                    RS485_Tx(ymSendBuf,popSize);
                }
                else if(ymPipe == PIPE_NET)
                {
                    ZY_UdpSend(ymSendBuf,popSize);
                }
                else
                {
                    CDC_Transmit_FS(ymSendBuf,popSize);
                    RS485_Tx(ymSendBuf,popSize);
                    ZY_UdpSend(ymSendBuf,popSize);
                }

                if(popSize < 64)    // send cplt
                {
                    break;
                }
            }
        }

        ledTick+=5;
        if(ledTick >= ledFre)
        {
          ledTick = 0;
          whichLed++;
          whichLed &= 0x01;
          switch(whichLed)
          {
              case 0:
                 blinkLed1(ledFre,1);
              break;
              case 1:
                 blinkLed2(ledFre,1);
              break;
          }
        }
        updateLeds();
//      rt_thread_delay_until(&lastTick,1);
        rt_thread_delay(5);
    }
}
/* USER CODE END 4 */

/**
  * @brief  Period elapsed callback in non blocking mode
  * @note   This function is called  when TIM6 interrupt took place, inside
  * HAL_TIM_IRQHandler(). It makes a direct call to HAL_IncTick() to increment
  * a global variable "uwTick" used as application time base.
  * @param  htim : TIM handle
  * @retval None
  */
void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim)
{
  /* USER CODE BEGIN Callback 0 */

  /* USER CODE END Callback 0 */
  if (htim->Instance == TIM6) {
    HAL_IncTick();
  }
  /* USER CODE BEGIN Callback 1 */

  /* USER CODE END Callback 1 */
}

/**
  * @brief  This function is executed in case of error occurrence.
  * @retval None
  */
void Error_Handler(void)
{
  /* USER CODE BEGIN Error_Handler_Debug */
    /* User can add his own implementation to report the HAL error return state */
    __disable_irq();
    while (1)
    {
    }
  /* USER CODE END Error_Handler_Debug */
}

#ifdef  USE_FULL_ASSERT
/**
  * @brief  Reports the name of the source file and the source line number
  *         where the assert_param error has occurred.
  * @param  file: pointer to the source file name
  * @param  line: assert_param error line source number
  * @retval None
  */
void assert_failed(uint8_t *file, uint32_t line)
{
  /* USER CODE BEGIN 6 */
    /* User can add his own implementation to report the file name and line number,
     ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
  /* USER CODE END 6 */
}
#endif /* USE_FULL_ASSERT */
